package com.wanjia.admin.server.controller;

import com.wanjia.admin.server.mapper.AdminMapper;
import com.wanjia.admin.server.pojo.Admin;
import com.wanjia.project.commons.dto.Consts;
import com.wanjia.project.commons.dto.ResultDTO;
import com.wanjia.project.commons.dto.login.AdminLoginParam;
import com.wanjia.admin.server.service.AdminService;
import com.wanjia.project.commons.dto.login.RespBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.List;

@Api(tags = "AdminLoginController")
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private AdminService adminService;

    @Resource
    private AdminMapper adminMapper;

    @ApiOperation(value = "登录之后返回的Token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request) {
        return adminService.login(adminLoginParam.getAccount(), adminLoginParam.getPassword(), adminLoginParam.getCode(), request);
    }


    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("/info")
    public Admin getAdminInfo(Principal principal) {
        if (principal != null) {
            String username = principal.getName();
            Admin admin = adminService.getAdminByUserName(username);
            // 将用户名密码设置null，安全性。
            admin.setAdminPwd(null);
            return admin;
        }
        return null;
    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout() {
        return RespBean.success("注销成功!");
    }



    @ApiOperation(value = "条件查询")
    @GetMapping("/selectByProperties")
    public RespBean selectByProperties(@RequestBody Admin admin){
        List<Admin> adminList = adminMapper.selectByProperties(admin);
        System.out.println(adminList);
        if(adminList!= null){
            return new RespBean(Consts.ResultCode.SUCCESS,"查询成功",adminList);
        }else {
            return new RespBean(Consts.ResultCode.FAIL,"查询失败",null);
        }
    }

    @ApiOperation(value = "新增管理员")
    @PostMapping("/addAdmin")
    public ResultDTO addAdmin(@RequestBody Admin admin){
        int i = adminMapper.insert(admin);
        System.out.println(i);
        if(i>0){
            return new ResultDTO(Consts.ResultCode.SUCCESS,"添加成功",i);
        }else {
            return new ResultDTO(Consts.ResultCode.FAIL,"添加失败",null);
        }
    }

    @ApiOperation(value = "删除管理员")
    @DeleteMapping("/delAdmin")
    public ResultDTO killAdmin(Integer id){
        int i = adminMapper.deleteById(id);
        System.out.println(i);
        if(i>0){
            return new ResultDTO(Consts.ResultCode.SUCCESS,"删除成功",null);
        }else {
            return new ResultDTO(Consts.ResultCode.FAIL,"删除失败",null);
        }
    }
}
